package org.web.common.sso.server.biz;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.web.base.domain.ResultDO;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ResultHelper;
import org.web.common.sso.server.config.SSOServerConfig;
import org.web.common.sso.server.controller.info.SsoMessageInfoEnum;
import org.web.common.sso.server.helper.redis.CacheSessionDO;
import org.web.common.sso.server.helper.redis.SsoServerRedisEnum;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service("redisTokenBiz")
public class RedisTokenBizImpl extends AbstractTokenBiz {

    @Resource
    private SSOServerConfig ssoServerConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultDO<CacheSessionDO> exchangeToken(String token) {
        ResultDO<CacheSessionDO> resultDO = new ResultDO();
        String value = stringRedisTemplate.opsForValue().get(SsoServerRedisEnum.SESSION_TOKEN.getKeyPrefix() + token);
        if (StringUtils.isEmpty(value)) {
            // 缓存中获取不到token的场合，认定token信息失效。
            ResultHelper.buildResultDOByResultMessageEnum(resultDO, ResultMessageEnum.DATA_LOSE_EFFICACY, SsoMessageInfoEnum.getSessionByToken_cash_missing.getMessage(), null);
            return resultDO;
        }
        Gson gson = new Gson();
        CacheSessionDO cacheSessionDO = gson.fromJson(value, CacheSessionDO.class);
        resultDO.setDomain(cacheSessionDO);
        return resultDO;
    }

    @Override
    public void refreshToken(String token, CacheSessionDO cacheSessionDO) {
        stringRedisTemplate.opsForValue().set(SsoServerRedisEnum.SESSION_TOKEN.getKeyPrefix() + token, new Gson().toJson(cacheSessionDO), ssoServerConfig.getInCashTime(), TimeUnit.MINUTES);
    }
}
